package lib
import (
	//"fmt"
	"os"
	"sync"
	_cache "github.com/funlake/gopkg/cache"
	"api/conf"
)

var (
	cache *Cache
	cacheSync sync.Once
	REDIS_PREFIX,_ = conf.GetConfig().Get("app").GetString("cache_prefix","gateway")
	//localCache = map[string] string{}
)
func initCache() {
	cacheSync.Do(func() {
		timercache := _cache.NewTimerCacheRedis()
		redisStore := &_cache.KvStoreRedis{}
		redisStore.Connect(os.Getenv("PQ_REDIS_HOST")+":"+os.Getenv("PQ_REDIS_PORT"),os.Getenv("PQ_REDIS_PASSWORD"))
		timercache.SetStore(redisStore)
		cache = &Cache{timercache:timercache}
	})
}
func NewCache() *Cache {
	initCache()
	return cache
}
//var refreshTimer = map[string] *time.Ticker{}
type Cache struct {
	timercache *_cache.TimerCacheRedis
}
func (this *Cache) Flush(){
	this.timercache.Flush()
}

func (this *Cache) GetUpstream(vk string) (string,error){
	//return this.HashGet("gateway:proxy",vk,60)
	return this.timercache.Get(REDIS_PREFIX+":proxy",vk,300)
}
func (this *Cache) GetMultiUpstream(vk string) (string,error){
	return this.timercache.Get(REDIS_PREFIX+":multiproxy",vk,600)
}
func (this *Cache) GetAcl(vk string) (string,error){
	return this.timercache.Get(REDIS_PREFIX+":acl",vk,120)
}
func (this *Cache) GetAclCheck(vk string) (string,error)  {
	return this.timercache.Get(REDIS_PREFIX+":aclignore",vk,86400)
}
func (this *Cache) GetJwtIgnore(vk string) (string,error)  {
	return this.timercache.Get(REDIS_PREFIX+":jwtignore",vk,86400)
}
func (this *Cache) GetRateLimit(vk string) (string,error){
	return this.timercache.Get(REDIS_PREFIX+":ratelimit",vk,60)
}
func (this *Cache) SetRateLimitLeft(vk string ,vv string)  (error){
	_,err:= this.timercache.GetStore().HashSet(REDIS_PREFIX+":ratelimitleft",vk,vv)
	return err
}
func (this *Cache) GetRateLimitLeft(vk string )  (string,error){
	return this.timercache.Get(REDIS_PREFIX+":ratelimitleft",vk,60)
}
func (this *Cache) GetAppInfo(access_token string) (string,error) {
	return this.timercache.Get("","OPEN_token:"+access_token,30)
}
func (this *Cache) GetCircuitBreakerSetting(service string) (string,error){
	return this.timercache.Get(REDIS_PREFIX+":circuitbreaker",service ,60)
}